﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BudgetMealsUI.Models;
using BudgetMealsModels.Entities;
using BudgetMealsModels.Abstract;

namespace BudgetMealsUI.Controllers
{
    public class HomeController : Controller
    {
        private IUserRepository repo;
        private IRecipeRepository recRepo;
        private int pageSize = 12;
        public HomeController(IUserRepository repository, IRecipeRepository recipeRepo)
        {
            repo = repository;
            recRepo = recipeRepo;
        }

        public ActionResult Index(int page = 1)
        {
            ListViewModel<Recipe> model = new ListViewModel<Recipe>
            {
                Info = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = pageSize,
                    TotalItems = recRepo.Recipes.Count()
                },
                PageItems = recRepo.Recipes.OrderBy(x => x.RecipeID).Skip(pageSize * (page - 1)).Take(pageSize)
            };
            return View(model);
        }

        public ActionResult Login(String url)
        {
            return View(new LoginViewModel()
                {
                    RedirectURL = url
                });
        }
        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            bool result = Membership.ValidateUser(model.Username, model.Password);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
                User user = repo.Users.FirstOrDefault(x => x.UserName == model.Username);
                HttpContext.Session["CurrentUser"] = user.UserID;
                HttpContext.Session["CurrentUserName"] = user.UserName;
                if(model.RedirectURL != null)
                    return Redirect(model.RedirectURL);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "Incorrect username/password");
            model.Password = "";
            return View(model);
        }
        public ActionResult Logout()
        {
            Session.RemoveAll();
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
    }
}
